﻿using System;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows.Forms;

namespace Microsoft.Win32
{
	internal static partial class NativeMethods
	{
		[SuppressUnmanagedCodeSecurity]
		internal class ThemingScope : IDisposable
		{
			private static IntPtr hActCtx;
			private IntPtr localCookie;

			public ThemingScope()
			{
				if (hActCtx == IntPtr.Zero)
					ThemingScope.GetCurrentActCtx(out hActCtx);
				localCookie = Activate();
			}

			public void Dispose()
			{
				if (localCookie != IntPtr.Zero)
					Deactivate(localCookie);
			}

			public static IntPtr Activate()
			{
				IntPtr ret = IntPtr.Zero;
				if (((Application.RenderWithVisualStyles && hActCtx != IntPtr.Zero) && OSFeature.Feature.IsPresent(OSFeature.Themes)) && !ActivateActCtx(hActCtx, out ret))
					ret = IntPtr.Zero;
				return ret;
			}

			[DllImport("kernel32.dll")]
			private static extern bool ActivateActCtx(IntPtr hActCtx, out IntPtr lpCookie);

			public static IntPtr Deactivate(IntPtr userCookie)
			{
				if (((userCookie != IntPtr.Zero) && OSFeature.Feature.IsPresent(OSFeature.Themes)) && DeactivateActCtx(0, userCookie))
					userCookie = IntPtr.Zero;
				return userCookie;
			}

			[DllImport("kernel32.dll")]
			private static extern bool DeactivateActCtx(int dwFlags, IntPtr lpCookie);

			[DllImport("kernel32.dll")]
			private static extern bool GetCurrentActCtx(out IntPtr handle);
		}
	}
}
